package com.info.zhiduoduo.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;

import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class MapUtil {

	/**
	 * 将对象转为{@code Map<String, Object>} 形式的数据
	 */
	public static Map<String, Object> obj2ObjMap(Object obj) {
		HashMap<String, Object> map = Maps.newHashMap();
		JSONObject jo = (JSONObject) JSONObject.toJSON(obj);
		jo.forEach((k, v) -> {
			if (v != null) {
				map.put(k, v);
			}
		});
		return map;
	}

	/**
	 * 将对象转为{@code Map<String, String>} 形式的数据
	 */
	public static Map<String, String> obj2StrMap(Object obj) {
		HashMap<String, String> map = Maps.newHashMap();
		return addValue2Map(map, obj, false, true);
	}

	public static TreeMap<String, String> obj2StrTreeMap(Object obj, boolean addEmptyStr) {
		TreeMap<String, String> map = Maps.newTreeMap();
		return (TreeMap<String, String>) addValue2Map(map, obj, false, addEmptyStr);
	}

	public static Map<String, String> addValue2Map(Map<String, String> map, Object obj, boolean addNullValue, boolean addEmptyStr) {
		JSONObject jo = JSON.parseObject(JSON.toJSONString(obj));
		jo.forEach((k, v) -> {
			if (v == null) {
				if (addNullValue) map.put(k, null);
			} else {
				String value = String.valueOf(v);
				if (StringUtil.isEmpty(value)) {
					if (addEmptyStr) map.put(k, value);
				} else {
					map.put(k, value);
				}
			}
		});
		return map;
	}

	/**
	 * 将{@code Map<String, Object>}转为{@code Map<String, String>} 形式的数据
	 */
	public static Map<String, String> map2StrMap(Map<String, Object> objMap) {
		HashMap<String, String> strMap = Maps.newHashMap();
		objMap.forEach((k, v) -> {
			if (v != null) {
				strMap.put(k, String.valueOf(v));
			}
		});
		return strMap;
	}

	/**
	 * 将map中的KV对拼接成字符串.
	 * <p> 返回用&拼接的字符串. 一般用于签名
	 *
	 * @param map
	 * @return 格式为: key1=value1&key2=value2
	 */
	public static String map2String(Map<String, String> map) {
		return map.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue()).collect(Collectors.joining("&"));
	}

	public static boolean isAllValueEmpty(Map<Integer, String> map) {
		if (CollectionUtils.isEmpty(map)) return true;
		List<String> list = map.values().stream().filter(StringUtil::isNotEmpty).collect(Collectors.toList());
		return CollectionUtils.isEmpty(list);
	}
}
